import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { HistoryRecord } from '../types/editor';

export const useEditorStore = defineStore('editor', () => {
  // 状态
  const content = ref('');
  const selectedText = ref('');
  const cursorPosition = ref(0);
  const history = ref<HistoryRecord[]>([]);
  const historyIndex = ref(-1);
  const isFullscreen = ref(false);
  const isPreviewVisible = ref(true);
  
  // Getters
  const canUndo = computed(() => historyIndex.value > 0);
  const canRedo = computed(() => historyIndex.value < history.value.length - 1);
  
  // Actions
  function updateContent(newContent: string) {
    content.value = newContent;
    addHistory(newContent);
  }
  
  function addHistory(newContent: string) {
    if (history.value.length === 0 || history.value[historyIndex.value]?.content !== newContent) {
      // 如果历史记录中有未来的记录（由于撤销操作），则删除它们
      history.value = history.value.slice(0, historyIndex.value + 1);
      history.value.push({
        content: newContent,
        timestamp: Date.now()
      });
      historyIndex.value++;
    }
  }
  
  function undo() {
    if (canUndo.value) {
      historyIndex.value--;
      content.value = history.value[historyIndex.value].content;
    }
  }
  
  function redo() {
    if (canRedo.value) {
      historyIndex.value++;
      content.value = history.value[historyIndex.value].content;
    }
  }
  
  function setSelectedText(text: string) {
    selectedText.value = text;
  }
  
  function setCursorPosition(position: number) {
    cursorPosition.value = position;
  }
  
  function toggleFullscreen() {
    isFullscreen.value = !isFullscreen.value;
  }
  
  function togglePreview() {
    isPreviewVisible.value = !isPreviewVisible.value;
  }
  
  return {
    content,
    selectedText,
    cursorPosition,
    history,
    historyIndex,
    isFullscreen,
    isPreviewVisible,
    canUndo,
    canRedo,
    updateContent,
    addHistory,
    undo,
    redo,
    setSelectedText,
    setCursorPosition,
    toggleFullscreen,
    togglePreview,
  };
});